<?php

namespace app\common\model;


use think\Db;
use think\Model;

class Message extends Model
{
    const MARK_ALL = 0;     //全部
    const MARK_STORE = 1;   //供应商
    const MARK_USER  = 2;   //普通用户

    /**
     * @param array $where
     * @param $page
     * 系统消息列表
     */
    public function message_list($where = [],$page,$uid)
    {
        $list = $this->where($where)
                    ->field('id,title,create_time')
                     ->order('create_time desc')
                     ->page($page,10)
                     ->select();
        $list = collection($list)->toArray();
        foreach ($list as &$value){
            $value['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
            $value['is_read'] = $this->is_read($value['id'],$uid);
        }
        return $list;
    }

    /**
     * @param $where
     * @param $uid
     * 系统消息详情
     */
    public function details($where,$uid)
    {
        $info = $this->where($where)
                     ->field('id,title,create_time,content')
                     ->find();
        if (!$info){
            return $info;
        }
        $info = $info->toArray();
        $info['create_time'] = date('Y-m-d H:i:s',$info['create_time']);
        $map = [
            'message_id' => $where['id'],
            'user_mark'  => self::MARK_USER,
            'u_id' => $uid
            ];

        if (!$this->is_read($where['id'],$uid)){
            $data = [
                'message_id' => $where['id'],
                'user_mark'  => self::MARK_USER,
                'u_id' => $uid,
                'read_time' => time()
            ];
            Db::name('message_read')->insert($data);
        }

        return $info;
    }

    /**
     * @param $id
     * @param $uid
     * @return bool
     * 是否已读
     */
    protected function is_read($id,$uid)
    {
        $where = [
            'message_id' => $id,
            'user_mark'  => self::MARK_USER,
            'u_id' => $uid
        ];
        $read =  Db::name('message_read')->where($where)->find();

        if ($read){
            return true;
        }else{
            return false;
        }
    }

}